package it.milanoeasy.gae;

import java.io.IOException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * 
 * @author fgaleaz
 *
 */
public class GenericServlet extends HttpServlet {
	private static Logger log = Logger.getLogger(GenericServlet.class.getName());
	/**
	 * 
	 */
	private static final long serialVersionUID = -6654023087990253337L;
	protected PersistenceManager persistenceManager;


	/**
	 * 
	 * @return
	 */
	public UserService getUserService(){
		UserService userService = null;
		try {
			userService = UserServiceFactory.getUserService();
		} catch(Exception e){
			System.out.println("Error: "+e.getMessage());
		}
		return userService;		
	}

	/**
	 * 
	 * @param req
	 * @return
	 */
	public String getNickName(HttpServletRequest req){
		UserService userService =getUserService();
		User user =null;
		String username="<user unknown>";
		if (userService!=null){
			user = userService.getCurrentUser();			
			if (user!=null){
				username=user.getNickname()+ "<"+user.getEmail()+">";
			}
		} else {
			Principal p=req.getUserPrincipal();
			username="<local> "+p.getName();
		}
		return username;
	}

	public it.milanoeasy.gae.User getUser(HttpServletRequest req){
		UserService userService =getUserService();
		User gUser=null;
		it.milanoeasy.gae.User user=null; 
		String username="<user unknown>";
		if (userService!=null && (gUser = userService.getCurrentUser())!=null){			
			user=new it.milanoeasy.gae.User(gUser);					
		} else {
			Principal p=req.getUserPrincipal();			
			user=new it.milanoeasy.gae.User();
			if (p!=null){
				username="<local> "+p.getName();
				user.setNickname(username);
			} else {				
				if (req.getRemoteUser()!=null){
					user.setNickname(req.getRemoteUser());
				}
				user.setAuthDomain(req.getRemoteHost()+":"+req.getRemotePort());
				user.setEmail(user.getNickname()+"@<"+req.getRemoteAddr()+">");
				String otherInfos="";
				String prop=null;
				Enumeration headerNames = req.getHeaderNames();
				while(headerNames.hasMoreElements()){					
					prop=(String)headerNames.nextElement();
					//					System.out.println(prop+": "+req.getHeader(prop));
				}
				/*
				 * Host: localhost:8888
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*//*;q=0.8
Accept-Language: it-it,it;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Referer: http://localhost:8888/index
Cookie: JSESSIONID=1h6lrn2sk2ira; __utma=111872281.252473522.1339838956.1339838956.1339838956.1; __utmb=111872281.23.10.1339838956; __utmc=111872281; __utmz=111872281.1339838956.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Content-Type: application/x-www-form-urlencoded
Content-Length: 306
Cache-Control: max-age=0
 */

				prop="User-Agent";				
				user.setUserId(req.getHeader(prop));
				prop="Accept-Language";				
				otherInfos+=prop+": "+req.getHeader(prop);				

				user.setFederatedIdentity(otherInfos);
			}

		}
		return user;
	}




	public boolean getCheckbox(HttpServletRequest request, String parameterName, boolean value) {
		String par=request.getParameter(parameterName);
		if (par==null || par.equalsIgnoreCase("")){
			return false;
		} else {
			return (par.equalsIgnoreCase("on"));
		}
	}


	public String getString(HttpServletRequest request, String parameterName, String value) {
		String par=request.getParameter(parameterName);
		if (par==null || par.equalsIgnoreCase("")){
			return value;			
		} else {					
			return par;
		}		
	}
		
	protected Double getDouble(String coor){
		coor=(coor!=null?coor:"0");
		Double dblCoor=new Double(0);
		try {
			dblCoor=Double.parseDouble(coor);
		} catch(Exception e){
			
		}
		return dblCoor;
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
	IOException {
		doPost(request,response);
	}

	protected void gotojsp(HttpServletRequest request,HttpServletResponse response, String target) {
		try {
			getServletContext().getRequestDispatcher(target).forward(request,response);
		} catch (ServletException e) {
			log.severe("Errore servlet: "+e.getMessage());
		} catch (IOException e) {
			log.severe("Errore I/O: "+e.getMessage());
		}
	}
	
	
	public PersistenceManager getPersistenceManager() {
		ServletContext context = getServletContext();		
		persistenceManager=(PersistenceManager)context.getAttribute("persistanceManager");
		if (persistenceManager==null){
			_getPersistenceManager();
			log.warning("Servlet: PersistenceManager by JDOHelper:"+persistenceManager);
		} else {
			if (persistenceManager.isClosed()) {
				_getPersistenceManager();
			}
			log.info("Servlet: PersistenceManager by context:"+persistenceManager);
		}
		context.setAttribute("persistanceManager",persistenceManager);
		
		return persistenceManager;
	}


	private void _getPersistenceManager() {
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("transactions-optional");
		persistenceManager = pmf.getPersistenceManager();
	}
}
